<template>
  <view class="user-page">
    <!-- 用户信息头部 -->
    <view class="user-header">
      <view class="user-info" @click="goToProfile">
        <image :src="userInfo.avatar || '/static/images/default-avatar.png'" class="avatar" />
        <view class="user-details">
          <text class="nickname">{{ userInfo.nickName || '未设置昵称' }}</text>
          <text class="phone">{{ maskPhone(userInfo.phoneNumber) || '未绑定手机号' }}</text>
        </view>
        <at-icon value="chevron-right" size="16" color="#fff"></at-icon>
      </view>
      
      <!-- 用户统计 -->
      <view class="user-stats">
        <view class="stat-item" @click="goToOrderList('all')">
          <text class="stat-number">{{ userStats.totalOrders }}</text>
          <text class="stat-label">全部订单</text>
        </view>
        <view class="stat-item" @click="goToFavorites">
          <text class="stat-number">{{ userStats.favoriteCount }}</text>
          <text class="stat-label">我的收藏</text>
        </view>
        <view class="stat-item" @click="goToCoupons">
          <text class="stat-number">{{ userStats.couponCount }}</text>
          <text class="stat-label">优惠券</text>
        </view>
      </view>
    </view>

    <!-- 订单状态 -->
    <view class="order-section">
      <view class="section-header">
        <text class="section-title">我的订单</text>
        <text class="more-btn" @click="goToOrderList('all')">查看全部</text>
      </view>
      <view class="order-status-list">
        <view 
          v-for="status in orderStatusList" 
          :key="status.type"
          class="order-status-item"
          @click="goToOrderList(status.type)"
        >
          <view class="status-icon">
            <at-icon :value="status.icon" size="24" color="#3478F6"></at-icon>
            <view v-if="status.count > 0" class="status-badge">{{ status.count }}</view>
          </view>
          <text class="status-label">{{ status.label }}</text>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-group">
        <view 
          v-for="menu in menuList" 
          :key="menu.key"
          class="menu-item"
          @click="handleMenuClick(menu)"
        >
          <view class="menu-icon">
            <at-icon :value="menu.icon" size="20" color="#3478F6"></at-icon>
          </view>
          <text class="menu-label">{{ menu.label }}</text>
          <view class="menu-extra">
            <text v-if="menu.extra" class="extra-text">{{ menu.extra }}</text>
            <at-icon value="chevron-right" size="14" color="#999"></at-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 设置菜单 -->
    <view class="menu-section">
      <view class="menu-group">
        <view 
          v-for="setting in settingList" 
          :key="setting.key"
          class="menu-item"
          @click="handleSettingClick(setting)"
        >
          <view class="menu-icon">
            <at-icon :value="setting.icon" size="20" color="#666"></at-icon>
          </view>
          <text class="menu-label">{{ setting.label }}</text>
          <view class="menu-extra">
            <at-icon value="chevron-right" size="14" color="#999"></at-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 退出登录 -->
    <view class="logout-section">
      <button class="logout-btn" @click="showLogoutConfirm">
        退出登录
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Taro, { useDidShow } from '@tarojs/taro'
import userApi from '@/api/user'
import orderApi from '@/api/order'
import { maskPhone, navigateTo, showError } from '@/utils'

// 响应式数据
const userInfo = ref({})
const userStats = ref({
  totalOrders: 0,
  favoriteCount: 0,
  couponCount: 0
})

// 订单状态列表
const orderStatusList = ref([
  { type: 'pending', label: '待付款', icon: 'clock', count: 0 },
  { type: 'paid', label: '待确认', icon: 'check-circle', count: 0 },
  { type: 'confirmed', label: '已确认', icon: 'bookmark', count: 0 },
  { type: 'completed', label: '已完成', icon: 'star', count: 0 }
])

// 功能菜单
const menuList = ref([
  { key: 'favorites', label: '我的收藏', icon: 'heart', extra: '' },
  { key: 'history', label: '浏览历史', icon: 'clock', extra: '' },
  { key: 'coupons', label: '优惠券', icon: 'tags', extra: '' },
  { key: 'address', label: '收货地址', icon: 'map-pin', extra: '' },
  { key: 'feedback', label: '意见反馈', icon: 'message-circle', extra: '' }
])

// 设置菜单
const settingList = ref([
  { key: 'about', label: '关于我们', icon: 'info' },
  { key: 'privacy', label: '隐私政策', icon: 'shield' },
  { key: 'terms', label: '用户协议', icon: 'file-text' },
  { key: 'contact', label: '联系客服', icon: 'phone' }
])

// 页面显示时加载数据
useDidShow(() => {
  loadUserData()
})

// 页面加载
onMounted(() => {
  loadUserData()
})

// 加载用户数据
const loadUserData = async () => {
  try {
    // 从本地存储获取用户信息
    const localUserInfo = Taro.getStorageSync('userInfo')
    if (localUserInfo) {
      userInfo.value = localUserInfo
    }

    // 获取最新用户信息
    const userResult = await userApi.getCurrentCustomer()
    if (userResult.code === 200) {
      userInfo.value = userResult.data
      Taro.setStorageSync('userInfo', userResult.data)
    }

    // 获取用户统计数据
    await loadUserStats()
    await loadOrderCounts()
  } catch (error) {
    console.error('加载用户数据失败:', error)
  }
}

// 加载用户统计
const loadUserStats = async () => {
  try {
    // TODO: 调用统计接口
    // const result = await userApi.getUserStats()
    // userStats.value = result.data
    
    // 模拟数据
    userStats.value = {
      totalOrders: 12,
      favoriteCount: 8,
      couponCount: 3
    }
  } catch (error) {
    console.error('加载用户统计失败:', error)
  }
}

// 加载订单数量
const loadOrderCounts = async () => {
  try {
    // TODO: 调用订单统计接口
    // const result = await orderApi.getOrderCounts()
    
    // 模拟数据
    orderStatusList.value[0].count = 2
    orderStatusList.value[1].count = 1
    orderStatusList.value[2].count = 3
    orderStatusList.value[3].count = 6
  } catch (error) {
    console.error('加载订单数量失败:', error)
  }
}

// 跳转到个人资料
const goToProfile = () => {
  navigateTo('/pages/user/profile')
}

// 跳转到订单列表
const goToOrderList = (status) => {
  navigateTo('/pages/order/list', { status })
}

// 跳转到收藏列表
const goToFavorites = () => {
  navigateTo('/pages/user/favorites')
}

// 跳转到优惠券
const goToCoupons = () => {
  navigateTo('/pages/user/coupons')
}

// 处理菜单点击
const handleMenuClick = (menu) => {
  switch (menu.key) {
    case 'favorites':
      navigateTo('/pages/user/favorites')
      break
    case 'history':
      navigateTo('/pages/user/history')
      break
    case 'coupons':
      navigateTo('/pages/user/coupons')
      break
    case 'address':
      navigateTo('/pages/user/address')
      break
    case 'feedback':
      navigateTo('/pages/user/feedback')
      break
    default:
      Taro.showToast({
        title: '功能开发中',
        icon: 'none'
      })
  }
}

// 处理设置点击
const handleSettingClick = (setting) => {
  switch (setting.key) {
    case 'about':
      navigateTo('/pages/about/index')
      break
    case 'privacy':
      navigateTo('/pages/agreement/privacy')
      break
    case 'terms':
      navigateTo('/pages/agreement/user')
      break
    case 'contact':
      showContactOptions()
      break
    default:
      Taro.showToast({
        title: '功能开发中',
        icon: 'none'
      })
  }
}

// 显示联系方式选项
const showContactOptions = () => {
  Taro.showActionSheet({
    itemList: ['拨打客服电话', '在线客服'],
    success: (res) => {
      if (res.tapIndex === 0) {
        Taro.makePhoneCall({
          phoneNumber: '400-123-4567'
        })
      } else if (res.tapIndex === 1) {
        Taro.showToast({
          title: '在线客服功能开发中',
          icon: 'none'
        })
      }
    }
  })
}

// 显示退出登录确认
const showLogoutConfirm = () => {
  Taro.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        logout()
      }
    }
  })
}

// 退出登录
const logout = () => {
  try {
    // 清除本地存储
    Taro.removeStorageSync('token')
    Taro.removeStorageSync('userInfo')
    
    Taro.showToast({
      title: '已退出登录',
      icon: 'success'
    })
    
    // 跳转到登录页
    setTimeout(() => {
      Taro.reLaunch({
        url: '/pages/login/index'
      })
    }, 1500)
  } catch (error) {
    console.error('退出登录失败:', error)
    showError('退出失败，请重试')
  }
}
</script>

<style lang="less">
.user-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.user-header {
  background: linear-gradient(135deg, #3478F6 0%, #5B9BF8 100%);
  padding: 40px 32px 32px;
  color: white;

  .user-info {
    display: flex;
    align-items: center;
    margin-bottom: 40px;

    .avatar {
      width: 120px;
      height: 120px;
      border-radius: 60px;
      margin-right: 24px;
    }

    .user-details {
      flex: 1;

      .nickname {
        font-size: 36px;
        font-weight: 600;
        display: block;
        margin-bottom: 8px;
      }

      .phone {
        font-size: 28px;
        opacity: 0.8;
        display: block;
      }
    }
  }

  .user-stats {
    display: flex;
    justify-content: space-around;

    .stat-item {
      text-align: center;

      .stat-number {
        font-size: 40px;
        font-weight: 600;
        display: block;
        margin-bottom: 8px;
      }

      .stat-label {
        font-size: 24px;
        opacity: 0.8;
        display: block;
      }
    }
  }
}

.order-section {
  background: white;
  margin: 24px 32px;
  border-radius: 16px;
  padding: 32px 24px;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32px;

    .section-title {
      font-size: 32px;
      font-weight: 600;
      color: #333;
    }

    .more-btn {
      font-size: 28px;
      color: #3478F6;
    }
  }

  .order-status-list {
    display: flex;
    justify-content: space-around;

    .order-status-item {
      display: flex;
      flex-direction: column;
      align-items: center;

      .status-icon {
        position: relative;
        margin-bottom: 16px;

        .status-badge {
          position: absolute;
          top: -8px;
          right: -8px;
          background: #FF4D4F;
          color: white;
          font-size: 20px;
          min-width: 32px;
          height: 32px;
          border-radius: 16px;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0 8px;
        }
      }

      .status-label {
        font-size: 24px;
        color: #666;
      }
    }
  }
}

.menu-section {
  margin: 0 32px 24px;

  .menu-group {
    background: white;
    border-radius: 16px;
    overflow: hidden;

    .menu-item {
      display: flex;
      align-items: center;
      padding: 32px 24px;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .menu-icon {
        width: 48px;
        height: 48px;
        background: #f8f9fa;
        border-radius: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 24px;
      }

      .menu-label {
        flex: 1;
        font-size: 28px;
        color: #333;
      }

      .menu-extra {
        display: flex;
        align-items: center;

        .extra-text {
          font-size: 24px;
          color: #999;
          margin-right: 16px;
        }
      }
    }
  }
}

.logout-section {
  padding: 0 32px 40px;

  .logout-btn {
    width: 100%;
    height: 88px;
    background: white;
    color: #FF4D4F;
    border: 1px solid #FF4D4F;
    border-radius: 44px;
    font-size: 32px;
    font-weight: 500;
  }
}
</style>